<?php
set_time_limit(0);
header("Content-type:text/html;charset=utf-8");
include dirname(dirname(__FILE__)).'/nn_logic/nl_common.func.php';
$dc = nl_get_dc(array(
    'db_policy' => NL_DB_WRITE,
    'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
));

$sql="select nns_id,nns_file_url from nns_medium_library_file where nns_cp_id = '89d903bc35dede724fd52c51437ff5fd' limit 100";

$result = nl_query_by_db($sql, $dc->db());
if(is_array($result) && !empty($result))
{
    $arr_file = $arr_cp = array();
    
    foreach ($result as $value)
    {
        $nns_file_url = trim($value['nns_file_url'],'/');
        $arr_url  = explode('/', $nns_file_url);
        if(!isset($arr_url[1]))
        {
            continue;
        }
        $cp_name = trim($arr_url[1]);
        if(strlen($cp_name) <1)
        {
            continue;
        }
        $cp_md5 = md5($cp_name);
        if(!isset($arr_cp[$cp_md5]))
        {
            $arr_cp[$cp_md5] = $cp_name;
        }
        $arr_file[$cp_md5][]=$value['nns_id'];
    }
    $date = date("Y-m-d H:i:s");
    foreach ($arr_cp as $key=>$value)
    {
        $sql_in = "insert into nns_medium_library_cp values('{$key}','{$value}','','','','','','','','','{$date}','{$date}','1')";
        echo $sql_in."<br>";
        nl_execute_by_db($sql_in, $dc->db());
    }
    foreach ($arr_file as $key_cp=>$value)
    {
        $sql_update = "update nns_medium_library_file set nns_cp_id='{$key_cp}' where nns_id in('".implode("','", $value)."')";
        echo $sql_update."<br>";
        nl_execute_by_db($sql_update, $dc->db());
    }
}
$sql="select nns_id from nns_medium_library_asset where nns_cp_id = '89d903bc35dede724fd52c51437ff5fd' limit 5000";
$result = nl_query_by_db($sql, $dc->db());
if(!is_array($result) || empty($result))
{
    die("ok");
}
foreach ($result as $value)
{
    $sql="select nns_cp_id from nns_medium_library_file where nns_asset_id = '{$value['nns_id']}' limit 1";
    $result_t = nl_query_by_db($sql, $dc->db());
    if(!is_array($result_t) || empty($result_t))
    {
        continue;
    }
    $sql_update = "update nns_medium_library_file set nns_cp_id='{$result_t[0]['nns_cp_id']}' where nns_id ='{$value['nns_id']}'";
    echo $sql_update."<br>";
     nl_execute_by_db($sql_update, $dc->db());
}